package cn.itcast.test;

import cn.itcast.Elastic.GoodsRepository;
import cn.itcast.pojo.Goods;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.Field;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringDataElasticSearch {
    @Autowired
    private ElasticsearchTemplate template;
    //创建索引库
    @Test
    public void createIndexTest(){
        //创建索引库，并制定实体类的字节码（创建索引）
        template.createIndex(Goods.class);
        //创建映射
        template.putMapping(Goods.class);

    }

    @Autowired
    private GoodsRepository goodsRepository;
    //批量新增
    @Test
    public void saveAll(){
        // 准备文档数据：
        List<Goods> list = new ArrayList<>();
        list.add(new Goods(1L, "小米手机7", "手机", "小米", 3299.00, "/13123.jpg"));
        list.add(new Goods(2L, "坚果手机R1", "手机", "锤子", 3699.00, "/13123.jpg"));
        list.add(new Goods(3L, "华为META10", "手机", "华为", 4499.00, "/13123.jpg"));
        list.add(new Goods(4L, "小米Mix2S", "手机", "小米", 4299.00, "/13123.jpg"));
        list.add(new Goods(5L, "荣耀V10", "手机", "华为", 2799.00, "/13123.jpg"));
        goodsRepository.saveAll(list);
    }
    //查询
    @Test
    public void testQuery(){
        Iterable<Goods> goods = goodsRepository.findAll();
        goods.forEach(System.out::println);
    }
    //删除
    @Test
    public void deleteQuery(){
        goodsRepository.deleteById(1l);
    }
    //根据范围查询
    @Test
    public void queryRange(){
        List<Goods> list = goodsRepository.findByPriceBetween(3000.00, 4000.00);
        list.forEach(System.out::println);
    }
    //原生查询
    @Test
    public void testNativeQuery(){
        //查询构建器,等同于SearchSourceQueryBuilder
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        //查询
        queryBuilder.withQuery(QueryBuilders.matchQuery("title", "小米手机"));
        //排序
        queryBuilder.withSort(SortBuilders.fieldSort("price").order(SortOrder.DESC));
        int page = 0;
        int size = 3;
        //分页
        queryBuilder.withPageable(PageRequest.of(page, size));
        //高亮
        queryBuilder.withHighlightFields(new HighlightBuilder.Field("title"));
        queryBuilder.withHighlightBuilder(new HighlightBuilder().preTags("<em>").postTags("</em>"));
        //聚合
        queryBuilder.addAggregation(AggregationBuilders.terms("brandAgg").field("brand"));

        //构建查询条件
        NativeSearchQuery searchQuery = queryBuilder.build();
        //搜索
        AggregatedPage<Goods> request = template.queryForPage(searchQuery, Goods.class);
        //总条数
        long elements = request.getTotalElements();
        System.out.println("elements = " + elements);
        //总页数
        int totalPages = request.getTotalPages();
        System.out.println("totalPages = " + totalPages);
        //当前页
        List<Goods> content = request.getContent();
        for (Goods goods : content) {
            System.out.println(goods);
        }
        //聚合结果
        Aggregations aggregations = request.getAggregations();
        Terms terms = aggregations.get("brandAgg");
        terms.getBuckets().forEach(b ->{
            System.out.println("品牌" + b.getKeyAsString());
            System.out.println("count"+b.getDocCount());
        });


    }
}
